package ing.gzq.service;

import ing.gzq.dao.CourseDao;
import ing.gzq.dao.UserDao;
import ing.gzq.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static ing.gzq.model.User.STUDENT_ROLE;
import static ing.gzq.model.User.TEACHER_ROLE;

@Service
public class AuthenticationService implements UserDetailsService{

    @Autowired
    UserDao userDao;

    @Autowired
    CourseDao courseDao;



    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            if(StringUtils.isEmpty(username)){
                return null;
            }
            User user = userDao.getUserByUsername(username);
            System.out.println("user = " + user);
            return user;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    public static User getUserInSecurityContext() {
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public boolean checkIfInCourse(Long courseId) {

        User user = getUserInSecurityContext();

        if(user.getCourseIdCache().contains(courseId))    //从缓存中获取
            return true;

        int count= user.isStudent()?
                courseDao.checkStudentInCourse(courseId,user.getUsername()):
                courseDao.checkTeacherInCourse(courseId,user.getUsername());

        if(count > 0 ){
            user.getCourseIdCache().add(courseId);         //添加缓存
            return true;
        }
        return false;
    }

    public boolean isTeacher(){
        return getUserInSecurityContext().isTeacher();
    }

    public boolean isStudent(){
        return getUserInSecurityContext().isStudent();
    }

}
